<template>
  <view class="contain_editaddress">
    <view class="sb">
      <nut-textarea
        @blur="autoAddress"
        style="height: 100rpx"
        v-model="autoAddressInfo"
        placeholder="请粘贴或输入文本，点击填”识别“自动识别姓名、联系方式和地址"
      />
      <view class="row">
        <view class="one">
          <image
            src="../../assets/images/sendAddress/fahuoxinxi_icon_yuying.png"
          ></image>
          <view class="text">语音识别</view>
          <image
            src="../../assets/images/sendAddress/fahuoxinxi_icon_tupian.png"
            style="margin-left: 48rpx"
          ></image>
          <view class="text">图片识别</view>
        </view>
        <view class="tow">
          <view class="button">粘贴并识别</view>
        </view>
      </view>
    </view>
    <view class="address_del">
      <nut-form :model-value="formData">
        <view class="rows">
          <nut-form-item label="真实姓名" label-align="center">
            <nut-input
              v-model="formData.name"
              placeholder="请填写真实姓名"
              :border="false"
            />
          </nut-form-item>
        </view>
        <view class="rows">
          <nut-form-item label="联系方式" label-align="center">
            <nut-input
              v-model="formData.phone"
              placeholder="请填写手机或座机号码"
              :border="false"
            />
          </nut-form-item>
        </view>
        <view class="rows">
          <nut-form-item label="省/市/区" label-align="center">
            <nut-input
              v-model="formData.preAdd"
              placeholder="请选择省/市/区"
              :border="false"
              @click="selectProvince"
            />
          </nut-form-item>
        </view>
        <view class="rows">
          <nut-form-item label="详细地址" label-align="center">
            <nut-input
              v-model="formData.address"
              placeholder="请填写精确到门牌的详细地址"
              :border="false"
            />
          </nut-form-item>
          <view class="address_icon" @click="positionAddress"></view>
        </view>
        <view class="footRows">
          <view class="default_address">
            <nut-checkbox v-model="formData.isdefault" label="复选框"
              >设为默认地址</nut-checkbox
            >
          </view>
          <span class="clear" @click="doClear">
            <Del2 /><span>清空当前</span>
          </span>
        </view>
      </nut-form>
      <SelectAddress
        :show="show"
        class="select_address"
        @selectAddress="selectAddress"
        :showonlyTF="isFlag"
        :addressInfo="addressInfo"
      />
      <!-- <input v-model="formData.name" class="input" type="text" placeholder="请输入联系人姓名或公司姓名">
      <input v-model="formData.phone" class="input" type="text" placeholder="请输入联系手机">


      <view class="get_address">
        <input v-model="formData.address" class="input address_Input" type="text" placeholder="请填写详细地址(精确到门牌号)">
        <view class="address_icon" @click="positionAddress"></view>
      </view>

      <view class="default_address" style="border-bottom: 1px solid #ccc">
        <span>设为默认地址</span>
        <nut-switch v-model="formData.isdefault" />
      </view> -->
    </view>

    <!-- <span class="clear" @click="doClear">清空当前</span>
    -->
    <view class="save" @click="save">确定</view>
  </view>
</template>

<script setup lang="ts">
import SelectAddress from "@/components/pages/addressBook/SelectAddress.vue";
import Taro from "@tarojs/taro";
import { ref } from "vue";
import { useRouter } from "@tarojs/taro";
import useAddressInfoStore from "@/store/addressbook";
import useUserInfoStore from "@/store/user";
import { AddressInfo } from "@/@api/AddressInfo";
import { AddressInfoDirection } from "@/type";
import { sub } from "../../assets/js/identify/sub";
import { Del2 } from "@nutui/icons-vue-taro";
import { $post, addressBookUpdate } from "@/@api";
export interface FormData {
  name: string;
  phone: string;
  address: string;
  //country: string[];
  isdefault: boolean;
  id: string;
  preAdd: string;
}
//下载qqmap-wx-jssdk,然后引入其中的js文件
let QQMapWX = require("../../assets/js/qqmap-wx-jssdk.min.js");

let qqmapsdk = new QQMapWX({
  key: "27FBZ-YPHH4-6M4UP-KLBGA-67TAV-UBBE2", // 必填
});
const show = ref<boolean>(false);
function selectProvince() {
  show.value = true;
}
const store = useAddressInfoStore();
const userStore = useUserInfoStore();
const autoAddressInfo = ref("");

const formData = ref<FormData>({
  name: "",
  phone: "",
  address: "",
  // country: [],
  isdefault: false,
  id: "",
  preAdd: "",
});
const addressInfo = ref<string[]>([]);

if (store.addressEditParameter.addressInfo?.btcaId) {
  console.log("yesyes");

  formData.value = {
    name: store.addressEditParameter.addressInfo?.preName,
    phone: store.addressEditParameter.addressInfo?.preTel,
    address: store.addressEditParameter.addressInfo?.preAddress.replace(
      store.addressEditParameter.addressInfo?.preAdd.split("/")[0] +
        store.addressEditParameter.addressInfo?.preAdd.split("/")[1] +
        store.addressEditParameter.addressInfo?.preAdd.split("/")[2],
      ""
    ),
    // country: store.addressEditParameter.addressInfo?.PREAREA.split(" "),
    preAdd:
      store.addressEditParameter.addressInfo?.preAdd.split("/")[0] +
      " " +
      store.addressEditParameter.addressInfo?.preAdd.split("/")[1] +
      " " +
      store.addressEditParameter.addressInfo?.preAdd.split("/")[2],
    isdefault:
      store.addressEditParameter.addressInfo?.isDefault === "1" ? true : false,
    id: store.addressEditParameter.addressInfo?.btcaId,
  };
  //addressInfo.value = store.addressEditParameter.addressInfo.PREAREA.split(" ");
}
// console.log(store.addressEditParameter.returnInfo, "1234567");
// if (store.addressEditParameter.returnInfo == null) {
//   console.log(7777);
// } else {
//   console.log(
//     store.addressEditParameter.returnInfo,
//     "store.addressEditParameter.returnInfo"
//   );
//   const latitude = store.addressEditParameter.returnInfo.latlng.lat;
//   const longitude = store.addressEditParameter.returnInfo.latlng.lng;
//   const addressName = store.addressEditParameter.returnInfo.poiname;
//   //逆地址解析,通过经纬度获取位置等信息
//   qqmapsdk.reverseGeocoder({
//     location: { latitude, longitude },
//     success: function (res) {
//       const province = res.result.address_component.province; //省
//       const city = res.result.address_component.city; //市
//       const district = res.result.address_component.district; //区

//       addressInfo.value = [province, city, district];
//       formData.value.address = addressName;
//       store.addressEditParameter.returnInfo = null;
//     },
//     fail: function (res) {
//       store.addressEditParameter.returnInfo = null;

//       console.log(res);
//     },
//   });
// }

const router = useRouter();
const isFlag = ref(
  router.params.type == AddressInfoDirection.Sender ? "true" : "false"
);

// 获取省市区
function selectAddress(val: string[]) {
  // formData.value.country = val;
  formData.value.preAdd = val[0] + " " + val[1] + " " + val[2];
  show.value = false;
}

function autoAddress() {
  const { city, county, datal, names, phone, province } = sub(
    autoAddressInfo.value
  );
  if (!city || !county || !province) {
    return Taro.showToast({
      icon: "none",
      title: "请输入正确地址",
    });
  }

  formData.value.address = datal;
  formData.value.name = names;
  // formData.value.country = [province, city, county];
  formData.value.phone = phone;
  // addressInfo.value = formData.value.country;
}

// 清空当前
function doClear() {
  formData.value = {
    name: "",
    phone: "",
    address: "",
    //  country: [],
    isdefault: false,
    id: "",
    preAdd: "",
  };
  addressInfo.value = [];
}
Taro.authorize({
  scope: "scope.userLocation",
  success() {
    console.log("获取权限成功");
  },
  fail() {
    console.log("获取权限失败");
  },
});
// 获取当前地理位置  选择地址服务
async function positionAddress() {
  console.log(process.env.TARO_ENV, "process.env.TARO_ENV");
  if (process.env.TARO_ENV === "h5") {
    Taro.navigateTo({
      url: "pages/addressBook/addressMap",
    });
  } else {
    Taro.chooseLocation({
      success(res) {
        const latitude = res.latitude;
        const longitude = res.longitude;

        const addressName = res.name;
        //逆地址解析,通过经纬度获取位置等信息
        qqmapsdk.reverseGeocoder({
          location: { latitude, longitude },
          success: function (res) {
            const province = res.result.address_component.province; //省
            const city = res.result.address_component.city; //市
            const district = res.result.address_component.district; //区

            addressInfo.value = [province, city, district];
            formData.value.address = addressName;
          },
          fail: function (res) {
            console.log(res);
          },
        });
      },
    });
  }
}

// 保存地址
async function save() {
  if (formData.value.name == "" || formData.value.name == null) {
    return Taro.showToast({
      icon: "none",
      title: "姓名不能为空",
    });
  }
  if (formData.value.phone == "" || formData.value.phone == null) {
    return Taro.showToast({
      icon: "none",
      title: "电话不能为空",
    });
  }
  let tel =
    /^((0\d{2,3}(-)?\d{7,8})|(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8})$/;
  if (!tel.test(formData.value.phone)) {
    return Taro.showToast({
      icon: "none",
      title: "请输入正确手机",
    });
  }
  if (formData.value.preAdd.length == 0) {
    return Taro.showToast({
      icon: "none",
      title: "请输入省市区",
    });
  }
  if (formData.value.address == "" || formData.value.address == null) {
    return Taro.showToast({
      icon: "none",
      title: "地址不能为空",
    });
  }
  let obj = {
    preAdd: "",
    preAddress: "",
    preAddressNote: null,
    preArea: null,
    preMobile: null,
    preName: "",
    preTel: "",
    infoType: "",
    isDefault: "",
    email: null,
    customerCode: "",
    btcaId: "",
  };
  if (router.params.type === AddressInfoDirection.Sender) {
    //发货地址
    // obj = {
    //   openid: userStore.openid,
    //   prename: formData.value.name, //发货人名字
    //   pretel: formData.value.phone, //发货人电话
    //   province: formData.value.country[0], //发货人省份
    //   city: formData.value.country[1], //发货人市
    //   quyu: formData.value.country[2], //发货人区
    //   preaddress: formData.value.address, //发货人详细地址
    //   prearea: formData.value.country.join(" "),
    //   optype: store.addressEditParameter.addressInfo?.ID ? "1" : "0",
    //   infotype: "发货人",
    //   isdefault: formData.value.isdefault ? "True" : "False",
    //   nickname: "nickname",
    //   preaddressnote: "",
    //   id: formData.value.id, //修改传值
    // };
    obj = {
      preAdd: formData.value.preAdd.replace(" ", "/").replace(" ", "/"),
      preAddress:
        formData.value.preAdd.replace(" ", "").replace(" ", "") +
        formData.value.address,
      preAddressNote: null,
      preArea: null,
      preMobile: null,
      preName: formData.value.name,
      preTel: formData.value.phone,
      infoType: "1",
      isDefault: formData.value.isdefault ? "1" : "0",
      email: null,
      customerCode: userStore.userInfo.customerCode,
      btcaId: formData.value.id,
    };
    if(!formData.value.id){
      obj.opFlag = '0'
    }
  } else {
    //收货地址
    obj = {
      preAdd: formData.value.preAdd.replace(" ", "/").replace(" ", "/"),
      preAddress:
        formData.value.preAdd.replace(" ", "").replace(" ", "") +
        formData.value.address,
      preAddressNote: null,
      preArea: null,
      preMobile: null,
      preName: formData.value.name,
      preTel: formData.value.phone,
      infoType: "2",
      isDefault: formData.value.isdefault ? "2" : "0",
      email: null,
      customerCode: userStore.userInfo.customerCode,
      btcaId: formData.value.id,
    };
  }

  const res = await addressBookUpdate(obj);
  console.log(res, "sss");
  if (res == 200) {
    Taro.navigateBack();
    Taro.showToast({
      icon: "success",
      title: "成功",
    });
  }
  if (store.addressEditParameter.addressInfo) {
    let savedAddressInfo: AddressInfo | null = {
      ...store.addressEditParameter.addressInfo,
      preName: formData.value.name,
      preTel: formData.value.phone,
      preAdd: formData.value.preAdd.replace(" ", "/").replace(" ", "/"),
      preAddress:
        formData.value.preAdd.replace(" ", "").replace(" ", "") +
        formData.value.address,
    };

    if (store.addressEditParameter.onEditComplete) {
      store.addressEditParameter.onEditComplete(savedAddressInfo);
    }
  }
  return;
  await $post<{
    code: number;
    infotype: string;
    message: string;
  }>("/sendgoos/addSender", {
    preinfos: JSON.stringify(obj),
  });

  Taro.navigateBack();

  Taro.showToast({
    icon: "success",
    title: "成功",
  });
}
</script>

<style lang="scss">
.nut-textarea {
  padding: 20rpx 20rpx;
}
.contain_editaddress {
  background-color: #f4f5f6;
  padding-top: 16rpx;
  box-sizing: border-box;
  padding-bottom: 50rpx;
  height: 100vh;
  .sb {
    background-color: white;
    width: 702rpx;
    height: 216rpx;
    margin-left: 24rpx;
    border-radius: 24rpx;
    .nut-textarea {
      border-radius: 24rpx;
    }
    .row {
      width: 100%;
      height: 56rpx;
      // background-color: red;
      display: flex;
      .one {
        width: 70%;
        height: 100%;
        display: flex;
        align-items: center;
        padding-left: 24rpx;
        box-sizing: border-box;
        image {
          width: 32rpx;
          height: 32rpx;
        }
        .text {
          font-size: 24rpx;
          font-family: PingFangSC-Regular;
        }
      }
      .tow {
        width: 30%;
        height: 100%;
        .button {
          width: 176rpx;
          height: 56rpx;
          border-radius: 28rpx;
          background: #0966ff;

          font-family: PingFang SC Bold;
          font-size: 26rpx;
          color: #ffffff;
          text-align: center;
          line-height: 56rpx;
        }
      }
    }
  }
  .address_del {
    border-radius: 24rpx;
    background-color: white;
    height: 520rpx;
    width: 702rpx;
    margin-left: 24rpx;
    margin-top: 16rpx;
    .footRows {
      width: 702rpx;
      height: 104rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .default_address {
        display: flex;
        justify-content: space-between;
        height: 50rpx;
        align-items: center;
        padding: 20rpx;
        .nut-checkbox__label {
          margin-left: 10rpx;
          font-family: PingFangSC-Regular;
          font-size: 24rpx;
          color: #666666;
        }
      }

      .clear {
        margin-right: 50rpx;
        color: #666;
        font-family: PingFangSC-Regular;
        font-size: 24rpx;
        display: flex;
        span {
          display: flex;
          align-items: center;
        }
      }
    }
    .rows {
      width: 702rpx;
      height: 103rpx;
      border-bottom: 1rpx solid #f4f5f6;
      display: flex;
      align-items: center;
      .nut-form-item__label {
        font-family: PingFang SC Medium;
        font-size: 28rpx;
        color: #666666;
      }
      .nut-input {
        font-family: PingFang SC;
        font-size: 28rpx;
        color: #999999;
      }
      .nut-cell {
        padding: 0;
      }
    }
  }
  .input {
    padding: 40rpx;
    border-bottom: 1px solid #ccc;
  }

  .save {
    position: fixed;
    bottom: 40rpx;
    width: 80%;
    height: 80rpx;
    left: 10%;
    border-radius: 40rpx;
    background-color: #0966ff;
    color: #fff;
    text-align: center;
    line-height: 80rpx;
  }

  .get_address {
    display: flex;
    border-bottom: 1px solid #ccc;

    .address_Input {
      flex: 1;
      padding: 40rpx;
      border-bottom: none;
    }
  }
}
.address_icon {
  width: 70rpx;
  height: 70rpx;
  line-height: 100rpx;
  background: url(../../assets/images/index/服务查询/wangdianchaxun_icon_chakanditu@2x.png)
    no-repeat center;
  margin-right: 25rpx;
}
</style>
